package com.service.utility.common;

import com.github.kevinsawicki.http.HttpRequest;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 图形验证码校验工具类
 */
public class PictureValidationCodeUtil {

    private static Logger logger = LoggerFactory.getLogger(PictureValidationCodeUtil.class);

    /**
     * 请求图形验证码校验
     *
     * @param pictureValidationCodeToken 图形验证码Token
     * @param pictureValidationCode      图形验证码内容
     */
    public static void validatePictureValidationCode(String URL, String pictureValidationCodeToken, String pictureValidationCode, String uuid) throws Exception {
        logger.info("校验图形验证码[uuid:{}, pictureValidationCodeToken:{}, pictureValidationCode:{}]", uuid, pictureValidationCodeToken, pictureValidationCode);
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", pictureValidationCodeToken);
        map.put("code", pictureValidationCode);
        String serialize = JsonStream.serialize(map);
        HttpRequest httpRequest = HttpRequest.post(URL)
                .acceptJson().contentType("application/json", "UTF-8")
                .send(serialize.getBytes());

        int httpCode = httpRequest.code();
        String body = httpRequest.body();
        logger.info("校验图形验证码[uuid:{}, responseCode:{}, responseBody:{}]", uuid, httpCode, body);

        Any anybody = JsonIterator.deserialize(body);
        int status = anybody.get("status").toInt();
        if (httpCode != HttpStatus.OK.value() || status != HttpStatus.OK.value()) {
            logger.info("图形验证码校验失败[uuid:{}, responseCode:{}, responseStatus:{}]", uuid, httpCode, status);
            throw new Exception("图形验证码校验失败 responseCode:" + httpCode + ", responseStatus:" + status);
        }

        logger.info("校验图形验证码校验成功[uuid:{}, pictureValidationCodeToken:{}, pictureValidationCode:{}]", uuid, pictureValidationCodeToken, pictureValidationCode);
    }
}
